<template>
    <div>

        <!--        搜索信息区域      -->
        <el-card style="width: 100%; height: 10vh;margin-bottom: 20px">
            <el-form :inline="true">

                <el-form-item label="分类名称" label-width="100px">
                    <el-input style="width: 175px" clearable v-model="searchName"
                              placeholder="请输入分类名称"></el-input>
                </el-form-item>

                <el-form-item label="分类介绍" label-width="100px">
                    <el-input style="width: 175px" clearable v-model="searchDetail"
                              placeholder="请输入分类介绍"></el-input>
                </el-form-item>

                <el-form-item label="状态" label-width="100px">
                    <el-select v-model="searchStatus" placeholder="请选择" clearable>
                        <el-option
                                v-for="item in statuss"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>

                <span style="float: right;margin-right: 10px">
                    <el-button style="margin-left: 20px" type="primary" @click="searchByManyCondition"
                               plain> 搜 索 </el-button>
                    <el-button @click="resetCondition"> 重 置</el-button>
                </span>


            </el-form>
        </el-card>

        <!--           分类信息表格        -->
        <el-card style="width: 100%; ">

            <!--          分类信息    标题-->
            <div slot="header" class="clearfix">
                <span style="font-weight: bold;font-size: 18px">分类信息</span>
                <el-button style="float: right;margin-right: 10px" type="danger" @click="deleteSelectCategorys"> 删除选中
                </el-button>
                <el-button style="float: right;margin-right: 20px" type="primary" plain @click="showAddCategory">
                    添加分类
                </el-button>
                <el-button style="float: right;margin-right: 10px" type="primary" plain @click="selectAll"> 查询所有分类
                </el-button>

                <!-- 添加信息的弹窗 -->
                <el-dialog title="添加分类" :visible.sync="dialogVisible_addCategory">
                    <el-form :model="add_category" size="medium" :rules="rules" ref="addCategoryRef"
                             :validate-on-rule-change="false">

                        <el-form-item prop="name" label="分类名称" label-width="100px">
                            <el-input v-model="add_category.name" autocomplete="off"
                                      placeholder="请输入分类名称"></el-input>
                        </el-form-item>

                        <el-form-item prop="detail" label="分类介绍" label-width="100px">
                            <el-input type="textarea" v-model="add_category.detail" placeholder="请输入分类介绍"
                                      style="width: 478px;margin-left: 20px"></el-input>
                        </el-form-item>

                        <el-form-item prop="status" label="状态" label-width="100px">
                            <el-select v-model="add_category.status" placeholder="请选择状态">
                                <el-option
                                        v-for="item in statuss"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>

                    </el-form>


                    <div slot="footer" class="dialog-footer">
                        <el-button type="warning" @click="resetAddCategory"> 重 置</el-button>
                        <el-button @click="cancelDialog_addCategory"> 取 消</el-button>
                        <el-button type="primary" @click="handleEdit_addCategory"> 确 定</el-button>
                    </div>

                </el-dialog>

                <!-- 删除分类信息的弹窗 -->
                <el-dialog
                        title="提示"
                        :visible.sync="dialogVisible_deleteSelect"
                        width="30%">
                    <span>真的要删除选中的所有信息吗？</span>
                    <span slot="footer" class="dialog-footer">
                        <el-button @click="dialogVisible_deleteSelect = false">取 消</el-button>
                        <el-button type="danger" @click="handleDeleteCategorys">确 定</el-button>
                    </span>
                </el-dialog>

            </div>


            <!--     分类信息列表    展示-->
            <template>
                <el-table height="390"
                          :header-cell-style="{fontSize: '14px','text-align':'center'}"
                          :cell-style="{'text-align':'center'}"
                          :data="categorys"
                          @selection-change="handleSelectCodeForTicket"
                          stripe
                          style="width: 100%">
                    <el-table-column
                            type="selection"
                            width="55">
                    </el-table-column>
                    <el-table-column width="100" label="序号" type="index" align="center"></el-table-column>
                    <el-table-column prop="name" label="分类名称" width="200px"></el-table-column>
                    <el-table-column prop="detail" label="分类介绍" show-overflow-tooltip
                                     width="450px"></el-table-column>
                    <el-table-column label="状态" width="100">
                        <template slot-scope="scope">
                            <el-tag type="danger" effect="dark" v-if="scope.row.status==0">已删除</el-tag>
                            <el-tag type="success" effect="dark" v-if="scope.row.status==1">生效中</el-tag>
                            <el-tag type="info" effect="dark" v-if="scope.row.status==2">无效中</el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作">
                        <!--     编辑  +  删除   分类-->
                        <template slot-scope="scope">
                            
                            <!--    编辑按钮    -->
                            <el-button type="primary" icon="el-icon-edit" circle
                                       @click="handleEditButton(scope.row)"></el-button>
                            <!--    删除按钮    -->
                            <el-button type="danger" icon="el-icon-delete" circle
                                       @click="handleDeleteButton(scope.row)"></el-button>


                            <!-- 删除分类信息的弹窗 -->
                            <el-dialog
                                    title="提示"
                                    :visible.sync="dialogVisible_delete"
                                    width="30%">
                                <span style="display: flex;">真的要删除这条信息吗？</span>
                                <span slot="footer" class="dialog-footer">
                                    <el-button @click="dialogVisible_delete = false">取 消</el-button>
                                    <el-button type="danger" @click="handleDeleteCategory">确 定</el-button>
                                </span>
                            </el-dialog>

                            <!-- 编辑信息的弹窗 -->
                            <el-dialog title="修改分类信息" :visible.sync="dialogFormVisible_edit">
                                <el-form :model="edit_category" size="medium" :rules="rules" ref="editCategoryRef"
                                         :validate-on-rule-change="false">

                                    <el-form-item prop="name" label="分类名称" label-width="100px">
                                        <el-input v-model="edit_category.name" autocomplete="off"
                                                  placeholder="请输入分类名称"></el-input>
                                    </el-form-item>

                                    <el-form-item prop="detail" label="分类介绍" label-width="100px">
                                        <el-input type="textarea" v-model="edit_category.detail"
                                                  placeholder="请输入分类介绍"
                                                  style="width: 478px;margin-left: 20px"></el-input>
                                    </el-form-item>

                                    <el-form-item prop="status" label="状态" label-width="100px">
                                        <el-select style="float: left;margin-left: 50px" v-model="edit_category.status"
                                                   placeholder="请选择状态">
                                            <el-option
                                                    v-for="item in statuss"
                                                    :key="item.value"
                                                    :label="item.label"
                                                    :value="item.value">
                                            </el-option>
                                        </el-select>
                                    </el-form-item>

                                </el-form>


                                <div slot="footer" class="dialog-footer">
                                    <el-button @click="cancelDialog_editCategory">取 消</el-button>
                                    <el-button type="primary" @click="handleEdit">确 定</el-button>
                                </div>

                            </el-dialog>
                        </template>
                    </el-table-column>

                    <el-table-column label="状态快捷操作" width="120px">
                        <template slot-scope="scope">
                            <!--    启用开关    -->
                            <el-switch
                                    style="margin-left: 20px"
                                    v-model="scope.row.status"
                                    :active-value="1"
                                    :inactive-value="2"
                                    active-color="#13ce66"
                                    inactive-color="#ff4949"
                                    @change='changeStatus(scope.row.id,scope.row.status)'
                            >
                            </el-switch>
                        </template>
                    </el-table-column>
                </el-table>

            </template>

            <el-pagination
                    style="float: right;margin: 20px 0"
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page.sync="currentPage"
                    :page-sizes="pageSizes"
                    :page-size="pageSize"
                    layout="total, sizes, prev, pager, next"
                    background
                    :total="total">
            </el-pagination>
            <!--
                            @size-change="handleSizeChange"          pageSize 改变时会触发
                            @current-change="handleCurrentChange"    currentPage 改变时会触发
            -->
        </el-card>

    </div>
</template>

<script>

export default {
    name: 'Category',
    data() {

        return {
            dialogFormVisible_edit: false,      // 编辑按钮弹出框
            dialogVisible_delete: false,        // 删除按钮弹出框
            dialogVisible_deleteSelect: false,  // 选中删除按钮弹出框
            dialogVisible_addCategory: false,      // 添加分类按钮弹出框

            categoryId: '',             // 存储被删除分类的id
            ids: [],                 // 存储被选中分类的id
            categorys: [],              // 存储分类信息

            edit_category: {},          // 存储当前操作的分类

            add_category: {
                status: []
            },                       // 存储添加的分类信息

            searchName: '',          // 存储搜索的分类名称
            searchDetail: '',         // 存储搜索的分类介绍
            searchStatus: '',       // 存储搜索的状态
            statuss: [{             // 存储所有状态       状态：0. 删除；1. 有效；2. 无效
                value: 0,
                label: '已删除'
            }, {
                value: 1,
                label: '生效中'
            }, {
                value: 2,
                label: '失效中'
            }],

            currentPage: 1,          // 当前页码
            pageSizes: [5, 10, 50, 100], // 每页显示条数
            pageSize: 5,             // 每页显示条数
            total: 0,                // 分类总数

            // 输入校验规则
            rules: {
                name: [
                    {required: true, message: '请输入分类介绍', trigger: 'blur'}
                ],
                detail: [
                    {required: true, message: '请填写店铺介绍', trigger: 'blur'}
                ],
                // status: [
                //     {required: true, message: '请选择状态', trigger: 'change', type: 'number'}
                // ],
            }

        }
    },
    mounted() {
        this.$request.get('/category/selectByPage?currentPage=1&pageSize=5').then(res => {
            if (res.code === '200') {
                this.categorys = res.data.list;
                this.total = res.data.total;
            } else {
                this.$message.error(res.msg);
            }
        })
    },


    methods: {
        // 启动开关的回调方法
        changeStatus(id, status) {
            console.log(id)
            console.log(status)
            // 发送请求
            this.$request.post('/category/updateStatus?id=' + id + '&status=' + status).then(res => {
                if (res.code === '200') {
                    this.$message.success('状态修改成功！');
                } else {
                    this.$message.error(res.msg);
                }
            })
        },

        // 移除表单的校验
        clearcheck(formName) {
            if (this.$refs[formName]) {
                this.$refs[formName].clearValidate()
            }
        },

        // 查询所有分类
        selectAll() {
            this.$request.get('/category/selectByPage?currentPage=' + this.currentPage + '&pageSize=' + this.pageSize).then(res => {
                if (res.code === '200') {
                    this.categorys = res.data.list;
                    this.total = res.data.total;
                    this.$message.success('查询成功');
                } else {
                    this.$message.error(res.msg);
                }
            })
        },

        // 添加分类
        handleEdit_addCategory() {
            // 输入检验
            this.$refs['addCategoryRef'].validate((valid) => {
                if (valid) {
                    // 校验通过
                    this.dialogVisible_addCategory = false;
                    // 添加分类
                    this.$request.post('/category/addCategory', this.add_category).then(res => {
                        this.add_category = {}
                        if (res.code === '200') {
                            this.$message.success('添加成功')
                            this.searchByManyConditionNoMsg()
                        } else {
                            this.$message.error(res.msg)
                        }
                    })
                } else {
                    this.$message.error('请输入完整信息')
                }
            })
        },


        // 取消添加分类
        cancelDialog_addCategory() {
            this.dialogVisible_addCategory = false;
        },

        // 重置添加的信息
        resetAddCategory() {
            this.add_category = {}
        },

        // 显示添加分类的弹出框
        showAddCategory() {
            this.clearcheck('addCategoryRef')
            this.dialogVisible_addCategory = true;
            this.add_category = {}
        },


        // 删除选中二次确认
        handleDeleteCategorys() {
            this.dialogVisible_deleteSelect = false;
            if (this.ids.length > 0) {
                // 删除选中
                this.$request.post('/category/deleteByIds', this.ids).then(res => {
                    if (res.code === '200') {
                        this.$message.success('删除成功');
                        // 刷新数据
                        this.searchByManyConditionNoMsg()
                    } else {
                        this.$message.error(res.msg);
                    }
                })
            } else {
                this.$message.info('请选择要删除的分类');
            }
        },


        // 删除选中二次提醒
        deleteSelectCategorys() {
            // 显示二次提醒弹窗
            this.dialogVisible_deleteSelect = true;
        },

        // 获取选中的分类id，
        // 并存储到 ids 数组中
        handleSelectCodeForTicket(val) {
            this.ids = val.map((item) => item.id);
        },


        // currentPage 改变时会触发
        handleCurrentChange(val) {
            // 获取  当前页 和 页面大小  currentPage、pageSize
            this.currentPage = val;

            // 发送请求获取相应数量的数据
            this.searchByManyConditionNoMsg()
        },


        //  pageSize 改变时会触发
        handleSizeChange(val) {
            // 获取  当前页 和 页面大小  currentPage、pageSize
            this.pageSize = val;
            this.currentPage = 1;

            // 发送请求获取相应数量的数据
            this.searchByManyConditionNoMsg()
        },


        // 条件查询
        searchByManyCondition() {

            // 如果状态未选择的话，调用A接口
            // 否则调用B接口
            // A接口不包括状态参数
            // B接口包括状态参数
            if (this.searchStatus !== '' && this.searchStatus !== null && this.searchStatus !== undefined) {
                // 如果searchStatus的值不为空，则将其转换为整数
                this.searchStatus = parseInt(this.searchStatus)
                this.$request.get('/category/selectByManyConditionInpage?currentPage=' + this.currentPage + '&pageSize=' + this.pageSize + '&name=' + this.searchName + '&detail=' + this.searchDetail + '&status=' + this.searchStatus).then(res => {
                    if (res.code === '200') {
                        this.categorys = res.data.list
                        this.total = res.data.total
                        this.$message.success("查询成功");
                    } else {
                        this.$message.error(res.msg);
                    }
                })
            } else {
                this.$request.get('/category/selectByManyConditionNoStatusInpage?currentPage=' + this.currentPage + '&pageSize=' + this.pageSize + '&name=' + this.searchName + '&detail=' + this.searchDetail).then(res => {
                    if (res.code === '200') {
                        this.categorys = res.data.list
                        this.total = res.data.total
                        this.$message.success("查询成功");
                    } else {
                        this.$message.error(res.msg);
                    }
                })
            }


        },

        // 条件查询 用来刷新数据不提示
        searchByManyConditionNoMsg() {
            // 如果状态未选择的话，调用A接口
            // 否则调用B接口
            // A接口不包括状态参数
            // B接口包括状态参数
            if (this.searchStatus !== '' && this.searchStatus !== null && this.searchStatus !== undefined) {
                // 如果searchStatus的值不为空，则将其转换为整数
                this.searchStatus = parseInt(this.searchStatus)
                this.$request.get('/category/selectByManyConditionInpage?currentPage=' + this.currentPage + '&pageSize=' + this.pageSize + '&name=' + this.searchName + '&detail=' + this.searchDetail + '&status=' + this.searchStatus).then(res => {
                    if (res.code === '200') {
                        this.categorys = res.data.list
                        this.total = res.data.total
                    } else {
                        this.$message.error(res.msg);
                    }
                })
            } else {
                this.$request.get('/category/selectByManyConditionNoStatusInpage?currentPage=' + this.currentPage + '&pageSize=' + this.pageSize + '&name=' + this.searchName + '&detail=' + this.searchDetail).then(res => {
                    if (res.code === '200') {
                        this.categorys = res.data.list
                        this.total = res.data.total
                    } else {
                        this.$message.error(res.msg);
                    }
                })
            }

        },

        // 分页查找
        selectByPage() {
            this.$request.get('/category/selectByPage?currentPage=' + this.currentPage + '&pageSize=' + this.pageSize).then(res => {
                if (res.code === '200') {
                    this.categorys = res.data.list
                    this.total = res.data.total
                } else {
                    this.$message.error(res.msg);
                }
            })
        },


        // 重置搜索条件
        resetCondition() {
            this.searchName = ''
            this.searchDetail = ''
            this.searchStatus = ''
            this.currentPage = 1
            this.pageSize = 5
            // 刷新获取分类信息
            this.$request.get('/category/selectByPage?currentPage=' + this.currentPage + '&pageSize=' + this.pageSize).then(res => {
                if (res.code === '200') {
                    this.categorys = res.data.list
                    this.total = res.data.total
                    this.$message.success("重置成功")
                } else {
                    this.$message.error(res.msg);
                }
            })
        },

        // 显示 修改分类信息    弹窗
        handleEditButton(category) {
            this.clearcheck('editCategoryRef')
            // 将当前行的分类数据传入form中
            this.edit_category = JSON.parse(JSON.stringify(category));
            // 状态转化
            let status = parseInt(category.status)
            for (let i = 0; i < this.statuss.length; i++) {
                if (status === this.statuss[i].value) {
                    this.edit_category.status = this.statuss[i].label
                    break
                }
            }
            // 显示弹窗
            this.dialogFormVisible_edit = true;
        },

        // 删除按钮二次提醒
        handleDeleteButton(category) {
            this.dialogVisible_delete = true
            this.categoryId = category.id
        },


        // 删除当前分类
        handleDeleteCategory() {
            this.dialogVisible_delete = false;
            this.$request.delete('/category/deleteById/' + this.categoryId).then(res => {
                if (res.code === '200') {
                    this.$message.success('删除成功');
                    this.categoryId = ''
                    // 重新加载数据
                    this.searchByManyConditionNoMsg()
                } else {
                    this.$message.error(res.msg);
                }
            })
        },


        // 取消修改信息
        cancelDialog_editCategory() {
            this.dialogFormVisible_edit = false;
            this.edit_category = {}
        },


        // 修改分类信息
        handleEdit() {

            // 状态转化
            for (let i = 0; i < this.statuss.length; i++) {
                if (this.edit_category.status === this.statuss[i].label) {
                    this.edit_category.status = this.statuss[i].value
                    break
                }
            }
            // 输入检验
            this.$refs['editCategoryRef'].validate((valid) => {
                if (valid) {
                    // 校验通过
                    this.dialogFormVisible_edit = false;
                    this.$request.put('/category/updateById', this.edit_category).then(res => {
                        // console.log(res)
                        if (res.code === '200') {
                            this.$message.success('修改成功');
                            this.edit_category = {}
                            // 重新加载数据
                            this.searchByManyConditionNoMsg()
                        } else {
                            this.$message.error(res.msg);
                        }
                    })
                } else {
                    this.$message.error('请输入完整信息')
                }
            })
        }
    }
}
</script>


<style>
.el-dialog__body {
    padding: 10px 30px;
}

input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
    -webkit-appearance: none;
}

input[type="number"] {
    -moz-appearance: textfield;
}


</style>